using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Material;
using WPF_MVVM_Test.Services.Material;

namespace WPF_MVVM_Test.MVVM_ViewModel.Material
{
    /// <summary>
    /// 物料新增ViewModel
    /// </summary>
    public class MaterialAddViewModel : BaseViewModel
    {
        private readonly MaterialService _materialService;
        private MVVM_Model.Material.Material _currentMaterial;
        private ObservableCollection<MaterialCategory> _materialCategories;
        private bool _isSaving = false;

        public MaterialAddViewModel()
        {
            _materialService = new MaterialService();
            _currentMaterial = new MVVM_Model.Material.Material
            {
                Id = Guid.NewGuid().ToString(),
                MaterialType = 1,
                Status = "启用",
                EffectiveDate = DateTime.Now,
                AlarmDays = 365,
                MaterialProperty = "外购"
            };

            // 初始化物料分类数据
            _materialCategories = new ObservableCollection<MaterialCategory>();
            LoadMaterialCategories();

            // 初始化命令
            SaveCommand = CreateCommand(ExecuteSave, CanExecuteSave);
            CancelCommand = CreateCommand(ExecuteCancel);
        }

        #region 属性

        /// <summary>
        /// 物料编号
        /// </summary>
        public string MaterialNumber
        {
            get => _currentMaterial.MaterialNumber;
            set
            {
                if (_currentMaterial.MaterialNumber != value)
                {
                    _currentMaterial.MaterialNumber = value;
                    OnPropertyChanged();
                    (SaveCommand as RelayCommand)?.RaiseCanExecuteChanged();
                }
            }
        }

        /// <summary>
        /// 物料名称
        /// </summary>
        public string MaterialName
        {
            get => _currentMaterial.MaterialName;
            set
            {
                if (_currentMaterial.MaterialName != value)
                {
                    _currentMaterial.MaterialName = value;
                    OnPropertyChanged();
                    (SaveCommand as RelayCommand)?.RaiseCanExecuteChanged();
                }
            }
        }

        /// <summary>
        /// 规格型号
        /// </summary>
        public string SpecificationModel
        {
            get => _currentMaterial.SpecificationModel;
            set
            {
                if (_currentMaterial.SpecificationModel != value)
                {
                    _currentMaterial.SpecificationModel = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 单位
        /// </summary>
        public string Unit
        {
            get => _currentMaterial.Unit;
            set
            {
                if (_currentMaterial.Unit != value)
                {
                    _currentMaterial.Unit = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 物料类型
        /// </summary>
        public int MaterialType
        {
            get => _currentMaterial.MaterialType;
            set
            {
                if (_currentMaterial.MaterialType != value)
                {
                    _currentMaterial.MaterialType = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 物料属性
        /// </summary>
        public string MaterialProperty
        {
            get => _currentMaterial.MaterialProperty;
            set
            {
                if (_currentMaterial.MaterialProperty != value)
                {
                    _currentMaterial.MaterialProperty = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 物料分类ID
        /// </summary>
        public string MaterialCategoryId
        {
            get => _currentMaterial.MaterialCategoryId;
            set
            {
                if (_currentMaterial.MaterialCategoryId != value)
                {
                    _currentMaterial.MaterialCategoryId = value;
                    OnPropertyChanged();
                    
                    // 更新分类名称
                    var category = GetAllCategories().FirstOrDefault(c => c.Id == value);
                    if (category != null)
                    {
                        _currentMaterial.MaterialCategoryName = category.CategoryName;
                    }
                    
                    (SaveCommand as RelayCommand)?.RaiseCanExecuteChanged();
                }
            }
        }

        /// <summary>
        /// 状态
        /// </summary>
        public string Status
        {
            get => _currentMaterial.Status;
            set
            {
                if (_currentMaterial.Status != value)
                {
                    _currentMaterial.Status = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 生效日期
        /// </summary>
        public DateTime EffectiveDate
        {
            get => _currentMaterial.EffectiveDate;
            set
            {
                if (_currentMaterial.EffectiveDate != value)
                {
                    _currentMaterial.EffectiveDate = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 生效单位
        /// </summary>
        public string EffectiveUnit
        {
            get => _currentMaterial.EffectiveUnit;
            set
            {
                if (_currentMaterial.EffectiveUnit != value)
                {
                    _currentMaterial.EffectiveUnit = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 预警天数
        /// </summary>
        public int AlarmDays
        {
            get => _currentMaterial.AlarmDays;
            set
            {
                if (_currentMaterial.AlarmDays != value)
                {
                    _currentMaterial.AlarmDays = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 库存上限
        /// </summary>
        public int StockUpperLimit
        {
            get => _currentMaterial.StockUpperLimit;
            set
            {
                if (_currentMaterial.StockUpperLimit != value)
                {
                    _currentMaterial.StockUpperLimit = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 库存下限
        /// </summary>
        public int StockLowerLimit
        {
            get => _currentMaterial.StockLowerLimit;
            set
            {
                if (_currentMaterial.StockLowerLimit != value)
                {
                    _currentMaterial.StockLowerLimit = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 采购价格
        /// </summary>
        public decimal PurchasePrice
        {
            get => _currentMaterial.PurchasePrice;
            set
            {
                if (_currentMaterial.PurchasePrice != value)
                {
                    _currentMaterial.PurchasePrice = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 销售价格
        /// </summary>
        public decimal SalesPrice
        {
            get => _currentMaterial.SalesPrice;
            set
            {
                if (_currentMaterial.SalesPrice != value)
                {
                    _currentMaterial.SalesPrice = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 备注
        /// </summary>
        public string Remarks
        {
            get => _currentMaterial.Remarks;
            set
            {
                if (_currentMaterial.Remarks != value)
                {
                    _currentMaterial.Remarks = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 物料分类列表（树形结构）
        /// </summary>
        public ObservableCollection<MaterialCategory> MaterialCategories
        {
            get => _materialCategories;
            set => SetProperty(ref _materialCategories, value);
        }

        /// <summary>
        /// 是否正在保存
        /// </summary>
        public bool IsSaving
        {
            get => _isSaving;
            set => SetProperty(ref _isSaving, value);
        }

        #endregion

        #region 命令

        public ICommand SaveCommand { get; }
        public ICommand CancelCommand { get; }

        #endregion

        #region 事件

        public event Action<bool>? RequestClose;

        #endregion

        #region 命令执行方法

        private async void ExecuteSave()
        {
            if (!CanExecuteSave())
                return;

            IsSaving = true;

            try
            {
                var response = await _materialService.AddMaterialAsync(_currentMaterial);
                
                if (response.IsSuc)
                {
                    System.Windows.MessageBox.Show("物料新增成功！", "成功", 
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                    RequestClose?.Invoke(true);
                }
                else
                {
                    System.Windows.MessageBox.Show($"物料新增失败：{response.Msg}", "错误", 
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"物料新增异常：{ex.Message}", "错误", 
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
            finally
            {
                IsSaving = false;
            }
        }

        private bool CanExecuteSave()
        {
            return !IsSaving && 
                   !string.IsNullOrWhiteSpace(MaterialNumber) && 
                   !string.IsNullOrWhiteSpace(MaterialName) &&
                   !string.IsNullOrWhiteSpace(MaterialCategoryId);
        }

        private void ExecuteCancel()
        {
            RequestClose?.Invoke(false);
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 加载物料分类数据
        /// </summary>
        private async void LoadMaterialCategories()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("开始加载物料分类数据...");
                var response = await _materialService.GetMaterialCategoryTreeAsync();
                
                System.Diagnostics.Debug.WriteLine($"API响应: IsSuc={response.IsSuc}, Code={response.Code}, Msg={response.Msg}");
                System.Diagnostics.Debug.WriteLine($"数据数量: {response.Data?.Count ?? 0}");
                
                if (response.IsSuc && response.Data != null)
                {
                    // 直接使用转换后的树形结构数据
                    MaterialCategories.Clear();
                    foreach (var category in response.Data)
                    {
                        System.Diagnostics.Debug.WriteLine($"添加分类: {category.CategoryName} (ID: {category.Id})");
                        MaterialCategories.Add(category);
                    }
                    
                    System.Diagnostics.Debug.WriteLine($"MaterialCategories总数: {MaterialCategories.Count}");
                }
                else
                {
                    System.Windows.MessageBox.Show($"加载物料分类失败：{response.Msg}", "提示", 
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                    
                    // 如果API失败，使用模拟数据
                    LoadMockData();
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载物料分类异常：{ex.Message}", "错误", 
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                
                System.Diagnostics.Debug.WriteLine($"加载异常: {ex.Message}");
                
                // 异常时使用模拟数据
                LoadMockData();
            }
        }

        /// <summary>
        /// 加载模拟数据
        /// </summary>
        private void LoadMockData()
        {
            System.Diagnostics.Debug.WriteLine("使用模拟数据...");
            var categories = MaterialCategory.GetMockData();
            
            MaterialCategories.Clear();
            foreach (var category in categories)
            {
                System.Diagnostics.Debug.WriteLine($"添加模拟分类: {category.CategoryName} (ID: {category.Id}, Level: {category.Level})");
                MaterialCategories.Add(category);
            }
            
            System.Diagnostics.Debug.WriteLine($"模拟数据总数: {MaterialCategories.Count}");
            
            // 触发属性更改通知，确保UI更新
            OnPropertyChanged(nameof(MaterialCategories));
        }



        /// <summary>
        /// 获取所有分类（扁平化）
        /// </summary>
        /// <param name="categories"></param>
        /// <returns></returns>
        private System.Collections.Generic.List<MaterialCategory> GetAllCategories(System.Collections.Generic.List<MaterialCategory>? categories = null)
        {
            if (categories == null)
                categories = MaterialCategory.GetMockData();

            var result = new System.Collections.Generic.List<MaterialCategory>();
            
            foreach (var category in categories)
            {
                result.Add(category);
                if (category.HasChildren)
                {
                    result.AddRange(GetAllCategories(category.Children));
                }
            }
            
            return result;
        }

        #endregion
    }
}